<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>观察者模式</title>
  </head>
  <body>
    <script>
      class Subject {
        constructor() {
          // 观察者列表
          this.observers = [];
        }

        add(observer) {
          this.observers.push(observer);
        }

        remove(observer) {
            this.observers = this.observers.filter((obs) => obs.name !== observer.name);
        }

        // 当本体发生改变时，通知每个观察者，调用观察者的更新方法
        changed() {
          console.log("Subject changed");
          this.observers.forEach((observer) => {
            observer.notify();
          });
        }
      }

      // 观察者
      class Observer {
        constructor(name) {
          this.name = name;
        }

        notify() {
          console.log(`Observer ${this.name} 的 notify 方法被调用了！`);
        }
      }

      const subject = new Subject();
      const Lucy = new Observer("Lucy");
      const Susan = new Observer("Susan");

      subject.add(Lucy);
      subject.add(Susan);
    </script>
  </body>
</html>
